package com.diors.game.engine.network;

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;

import com.diors.commons.network.AbstractConnection;
import com.diors.commons.network.AbstractServer;
import com.diors.commons.network.NetworkHandler;
import com.diors.commons.network.NetworkListener;
import com.diors.game.engine.thread.ThreadPoolManager;

/**
 * 游戏服务器
 * @author	darren.ouyang <ouyang.darren@gmail.com>
 * @date	2013-10-21
 * @version 1.0
 * @copyright Copyright (c) 2013, darren.ouyang
 */
public class GameServer extends AbstractServer
{
	static final Logger log = Logger.getLogger(GameServer.class);
	
	/* 当前服的所有连接 */
	protected final Map<Integer, AbstractConnection> conns;
	
	private static GameServer instance = new GameServer();
	
	public static GameServer getInstance()
	{
		return instance;
	}
	
	private GameServer ()
	{
		conns = Collections.synchronizedMap(new HashMap<Integer, AbstractConnection>());
		handler = new NetworkHandler<GameClient>(new GameConnFactory(), new GameListener());
		address = new InetSocketAddress("192.168.0.107", 8080);
	}
	
	/**
	 * 游戏监听器
	 * @author	darren.ouyang <ouyang.darren@gmail.com>
	 * @date	2013-10-21
	 * @version 1.0
	 * @copyright Copyright (c) 2013, darren.ouyang
	 */
	private class GameListener extends NetworkListener<GameClient>
	{

		@Override
		public void connected(GameClient conn) 
		{
			conns.put(conn.getBaseID(), conn);
			log.info(new StringBuilder("有新的连接建立--").append(conn).toString());
		}

		@Override
		public void close(GameClient conn, String info) 
		{
			conns.remove(conn.getBaseID());
			log.info(new StringBuilder("连接关闭--").append(conn).
					append("info[").append(info).append("]").toString());
		}

		@Override
		public boolean messageReceived(GameClient conn, ChannelBuffer buff) 
		{
			int length = 0;
			try
			{
				length = buff.readInt();
				ChannelBuffer _buff = buff.slice();
				_buff.writerIndex(length);
				buff.readerIndex(buff.readerIndex() + length);
				GameClientPacket packet = new GameClientPacket(conn, _buff);
				boolean result = packet.processData();
				if (result)
				{
					/* 将包处理加入到线程池 */
					ThreadPoolManager.getInstance().executeSelecter(1, packet);
					return Boolean.TRUE;
				}
				
				return Boolean.FALSE;
			}
			catch (Exception e) 
			{
				log.warn("解析客户端的包出错-连接" + conn + "包长:" + length, e);
				return Boolean.FALSE;
			}
		}
		
	}
}
